package com.aek.aekdroid;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

public class Helper {

	public static final String TAG = "Helper";
	public static final int NO = 0;
	public static final int YES = 1;

	public static CharSequence createDate(long timestamp) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(timestamp);
		Date d = c.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		return sdf.format(d);
	}

	public static Long getLongPref(SharedPreferences prefs, String key, long defaultValue) {
		String v = prefs.getString(key, String.valueOf(defaultValue));
		if (v != null) {
			try {
				return Long.parseLong(v);
			} catch (NumberFormatException e) {

			}
		}
		return defaultValue;
	}

	public static String getStringElementValue(Element el, String child, String defaultValue) {
		String v = defaultValue;
		try {
			v = ((Element) el.getElementsByTagName(child).item(0)).getChildNodes().item(0).getNodeValue();

			return v;

		} catch (Exception e) {
			v = el.getChildNodes().item(0).getNodeValue();
			return v != null ? v : defaultValue;
		}
	}

	public static Long getLongElementValue(Element el, String child, long defaultValue) {
		try {
			String v = ((Element) el.getElementsByTagName(child).item(0)).getChildNodes().item(0).getNodeValue();
			return Long.parseLong(v);
		} catch (Exception ex) {
			return defaultValue;
		}
	}

	public static int getIntElementValue(Element el, String child, int defaultValue) {
		try {
			String v = ((Element) el.getElementsByTagName(child).item(0)).getChildNodes().item(0).getNodeValue();

			return Integer.parseInt(v);
		} catch (Exception ex) {
			return defaultValue;
		}
	}

	public static ArrayList<Element> getElements(Element parent, String children) {
		NodeList nodelist = parent.getElementsByTagName(children);
		ArrayList<Element> elements = new ArrayList<Element>();
		int l = nodelist.getLength();
		for (int i = 0; i < l; i++) {
			Element element = (Element) nodelist.item(i);
			elements.add(element);
		}
		return elements;
	}

	public static Element getElement(Element parent, String name) {
		NodeList nodelist = parent.getElementsByTagName(name);
		if (nodelist.getLength() > 0) {
			return (Element) nodelist.item(0);
		}
		return null;
	}

	public static void updateNow(Context context) {
		Intent intent = new Intent(context, MatchUpdaterService.class);
		// TODO ADD manual extra
		intent.putExtra(MatchUpdaterService.MANUAL, true);
		PendingIntent pendingIntent = PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC, System.currentTimeMillis(), pendingIntent);
		MyLog.d("Menu", "Started an alarm now");
	}

	public static void setAlarm(String TAG, Context context, long interval) {
		MyLog.d(TAG, "Setting alarm");
		if (interval == -1) {
			interval = ((AekDroidApplication) context.getApplicationContext()).getInterval();
		}
		Intent intent = new Intent(context, MatchUpdaterService.class);
		PendingIntent pendingIntent = PendingIntent.getService(context, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		if (interval > 0) {
			alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), interval, pendingIntent);
			MyLog.d(TAG, "Started alarm with interval " + interval);
		} else {
			alarmManager.cancel(pendingIntent);
			MyLog.d(TAG, "Stopped alarm (interval " + interval + ")");
		}
	}

	static int confirm(Activity activity, String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		int answer = NO;
		builder.setMessage("Are you sure you want to exit?").setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();

					}
				}).setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();

					}
				});
		AlertDialog alert = builder.create();

		return answer;
	}

	public static void checkAdminPass(final Activity act, final String v) {
		MyLog.d(TAG, "Checking pass");

		Runnable r = new Runnable() {

			@Override
			public void run() {
				doAction();
			}

			private void doAction() {
				FileOutputStream fos = null;
				String url = WebAekDroid.ADMIN_URL + "&value=" + v;
				MyLog.d(TAG, "Reading " + url);
				try {
					URL u = new URL(url);
					URLConnection urlConnection = u.openConnection();
					BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());
					DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
					DocumentBuilder db = dbf.newDocumentBuilder();
					Document doc = db.parse(in);
					NodeList nodelist = doc.getElementsByTagName("check");
					Element root = (Element) nodelist.item(0);
					String value = root.getAttribute("value");
					File admin = new File(act.getFilesDir() + "/admin");
					if (!admin.delete()) {
						MyLog.d(TAG, "Could not delete admin file");
					}
					MyLog.d(TAG, "Response: " + value);
					if (value.equals("ok")) {
						fos = act.openFileOutput("admin", Context.MODE_PRIVATE);
						fos.write(1);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					e.printStackTrace();
				} catch (SAXException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					if (fos != null) {
						fos.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		};
		Thread t = new Thread(r);
		t.start();
	}

	public static void adminFunction(final Activity act, final String url) {

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				URL u;
				try {
					u = new URL(url);
					URLConnection urlConnection = u.openConnection();
					BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());
					DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
					DocumentBuilder db = dbf.newDocumentBuilder();
					Document doc = db.parse(in);
					NodeList nodelist = doc.getElementsByTagName("create");
					Element root = (Element) nodelist.item(0);
					String value = root.getAttribute("response");
					// Toast.makeText(act, value, Toast.LENGTH_SHORT).show();
					// MyLog.d(TAG, value);
					act.startActivity(new Intent(act, ScheduleActivity.class));
				} catch (MalformedURLException e) {
					MyLog.e(TAG, "Malformed URL " + url);
					e.printStackTrace();
				} catch (IOException e) {
					MyLog.e(TAG, "IO error");
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					MyLog.e(TAG, "WRONG RESPONSE");
					e.printStackTrace();
				} catch (SAXException e) {
					MyLog.e(TAG, "WRONG RESPONSE");
					e.printStackTrace();
				}
			}
		});
		t.start();
	}

	public static boolean isInArray(String str, String[] array) {
		for (int i = 0; i < array.length; i++) {
			if (str.equals(array[i])) {
				return true;
			}
		}
		return false;
	}

	public static boolean isNumeric(String num) {
		try {
			long lNum = Long.parseLong(num);
		} catch (NumberFormatException e) {
			return false;
		}
		return true;
	}

	public static String getDefaultPeriod() {
		int curYear;
		Calendar c = Calendar.getInstance();
		if (c.get(Calendar.MONTH) > 5) {
			curYear = c.get(Calendar.YEAR);
		} else {
			curYear = c.get(Calendar.YEAR) - 1;
		}

		return String.valueOf(curYear) + "-" + String.valueOf(curYear + 1);
	}

}
